package org.mifos.boss.business;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.mifos.boss.business.helper.BossDefinitionsToDomainObjectMapper;
import org.mifos.boss.definitions.customerregistration.Mobile2BossDataExchange;
import org.mifos.boss.domainmodel.Mobile2BossData;
import org.mifos.boss.domainmodel.MobileFileUpload;
import org.mifos.boss.persistence.BossPersistenceInterface;
import org.mifos.boss.util.BossUnmarshallerUtil;
import org.mifos.boss.util.MifosFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


@Transactional
@Repository(value="dataTransferBusiness")
public class DataTransferBusinessImpl extends BaseBossBusiness implements DataTransferBusinessInterface {

	protected static Logger logger = Logger.getLogger(DataTransferBusinessImpl.class);

	@Autowired
	@Qualifier("bossPersistence")
	BossPersistenceInterface bossPersistence;
	
	@Autowired
	@Qualifier("parser")
	BossUnmarshallerUtil parser;
	
	@Autowired
	@Qualifier("mobile2BossDataMapper")
	BossDefinitionsToDomainObjectMapper mobile2BossDataMapper;
	
/*	public Customer createCustomer(MobileFileUpload mobileFileUpload) {
//		customerPersistence.createCustomer(mobileFileUpload);
		
    	//test uplaoded file
    	logger.debug("test upload:\n" + mobileFileUpload.getFileData().getOriginalFilename());
    	
		MifosFileUtil.testDisplayFile(mobileFileUpload.getFileData());
		try{
			clientDataHandler(mobileFileUpload);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("couldnt parse the file");
			logger.error(e.getMessage(), e);
		}
//		return mobileFileUpload;
		return null;
	}*/

	private void clientDataHandler(MobileFileUpload mobileFileUpload) throws IOException{
		Mobile2BossDataExchange clientData = parser.clientDataParser(mobileFileUpload);
		Mobile2BossData mobile2BossData = mobile2BossDataMapper.transform(clientData);
		if (clientData != null)
			bossPersistence.saveClientExcahngeData(mobile2BossData);
	}

	public MobileFileUpload processUploadedData(MobileFileUpload mobileFileUpload) {
		// TODO Auto-generated method stub
		logger.debug("test upload:\n" + mobileFileUpload.getFileData().getOriginalFilename());
//    	testWebSer();
		MifosFileUtil.testDisplayFile(mobileFileUpload.getFileData());
		try{
			clientDataHandler(mobileFileUpload);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("couldnt parse the file");
			logger.error(e.getMessage(), e);
		}
		// mobileFileUpload can be set to successful status and returned.
		return mobileFileUpload;
	}
}
